import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog";
// pages/management/category-management/index.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    activeId: null,
    active: null,
    showPicker: false,
    columns: ["一次除皮", "二次除皮"],
    categoryList: []
  },

  onPickerChange(event) {
    const { value, index } = event.detail;
    const { categoryList } = this.data;
    categoryList[this.data.active]["peelingType"] = index + 1;
    categoryList[this.data.active]["peelingName"] = value;

    let params = this.data.categoryList[this.data.active];
    let url = "updateCateGory";
    wx.showLoading({
      title: "获取中..."
    });
    wx.$apis[url]({
      id: params.id,
      peelingType: params.peelingType
    }).then(() => {
      wx.showToast({
        title: "修改成功",
        duration: 2000
      }).then(() => {
        this.setData({
          showPicker: false
        });
        this.getData();
      });
    });
  },

  onCancel() {
    this.setData({
      showPicker: false
    });
  },

  // 编辑品类
  onEditCrop(e) {
    let active = e.currentTarget.dataset.index;
    let activeId = e.currentTarget.dataset.id;
    this.setData({
      active,
      activeId,
      showPicker: true
    });
  },

  // 添加品类
  toAddCrop() {
    wx.navigateTo({
      url: "/pages/management/add-category/index"
    });
  },

  onDelete(event) {
    let id = event.currentTarget.dataset.id;
    Dialog.confirm({
      message: "确定删除吗？"
    }).then(() => {
      this.delete(id);
    });
  },

  delete(id) {
    wx.showLoading({
      title: "删除中，请稍后..."
    });
    wx.$apis
      .deleteCropList({
        ids: [id]
      })
      .then((res) => {
        wx.showToast({
          title: "删除成功",
          icon: "success",
          duration: 1000
        }).then(() => {
          setTimeout(() => {
            this.getData();
          }, 1000);
        });
      });
  },

  // 获取页面数据
  getData() {
    wx.showLoading({
      title: "获取中..."
    });
    wx.$apis.getCropCategoriesByCompanyId(app.globalData.userInfo.companyData.companyId).then((res) => {
      if (!res.data) return false;
      let categoryList = res.data.filter((item) => item.varietyId);
      this.setData({
        categoryList: categoryList.map((item) => {
          // 有品种才是新数据
          if (item.varietyId) {
            return {
              ...item,
              value: item.peelingType === 1 ? "一次除皮" : "二次除皮"
            };
          }
        })
      });
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});
